//swren.c
#include "color_buffer.h"
#include <stdlib.h>
#include <stddef.h>
#include <Windows.h>
#include <MainWindow.h>

color_buffer::color_buffer(int w, int h)
: m_lpMemory(NULL)
, m_nSize(0)
{
	set_buffer_size(w,h);
}

void color_buffer::set_buffer_size(int w, int h)
{
	delete m_lpMemory;
	m_nSize = w*h;
	m_lpMemory = new int[m_nSize];
	m_nPitch = w;
}

void color_buffer::clear_color_buffer( int color )
{
	if(m_lpMemory)
	{
		for(int i=0; i<m_nSize; i++)
		{
			m_lpMemory[i] = color;
		}	
	}
}

void color_buffer::set_pixel_color( int x, int y, int color )
{
	int offset = y*m_nPitch+x;
	if(m_lpMemory && offset<m_nSize)
	{
		m_lpMemory[offset] = color;
	}
}

void color_buffer::draw_line( int x1, int y1, int x2, int y2, int color )
{
	int sx, sy; // steps of x,y
	if (x2>x1) 
		sx = x2-x1;
	else
		sx = x1-x2;

	if (y2>y1)
		sy = y2-y1;
	else
		sy = y1-y2;

	if (sx==0 && sy==0)
		return;

	int steps = sx;
	if (sy>sx)
		steps = sy;

	float dx = float(x2-x1)/float(steps);
	float dy = float(y2-y1)/float(steps);
	float x = x1;
	float y = y1;
	for (int i=0; i<steps; i++)
	{
		set_pixel_color(x, y, color);
		x+=dx;
		y+=dy;
	}
}

void color_buffer::draw( MainWindow* lpMainWnd )
{
	if(lpMainWnd && m_lpMemory)
	{
		//void DrawFrame(void* lpColorBuffer, int iBytes, RECT rcSrc, RECT rcDest );
		int w = m_nPitch;
		int h = m_nSize/w;
		RECT rc = {0, 0, w, h};
		lpMainWnd->DrawFrame(m_lpMemory, m_nSize, rc, rc);
	}
}

int mkcolor( int r, int g, int b )
{
	return ((int)(((BYTE)(b)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(r))<<16)));
}
